package de.koller.worlders.engine.tiles.data;

import de.koller.oceanFramework.tree.Child;
import de.koller.oceanFramework.tree.Mother;
import de.koller.oceanFramework.util.ColorIntUtil;
import de.koller.worlders.WSea;
import de.koller.worlders.engine.entity.deco.Deco;
import de.koller.worlders.engine.entity.fog.Fog;
import de.koller.worlders.engine.tiles.ITile;
import de.koller.worlders.engine.tiles.Tile;
import de.koller.worlders.engine.tiles.TileMap;

public class TileLoader extends WSea {
	
	@Mother private TileMap map;
	@Child public final MapDataDist mapDataDist = new MapDataDist();
	
	private final TileCreatorGen creatorMap = new TileCreatorGen();
	
	public void reloadData( boolean story ) {
		mapDataDist.reloadData();
	}
	
	public Tile load( int x, int y ) {	
		Tile t;
		ITile tc = null;
		
		try {
			tc = translateMapColor( this.getMapData( x, y ).getMapData( x, y ) );
		} catch( ArrayIndexOutOfBoundsException ex ) {
			tc = null;
		}
		
		if( tc != null )
			t = new Tile( x, y, tc );
		else {
			t = new Tile( x, y );
		}
		
		t.root = wroot;
		//setLighting( t, x, y );
		setDeco( t, x, y );
		setFog( t, x, y );
		
		map.getTileHolder().addTileNode( t );
		
		MapData md = this.getMapData( x, y );
		md.tileLoaded();
		t.assignedMapData = md;
		
		return t;
	}
	
	private void setDeco( Tile t, int x, int y ) {
		ITileCreator tc = creatorMap.getDecoCreator( ColorIntUtil.getGValue( this.getMapData( x, y ).getMapData( x, y ) ) );
		if( tc != null )
			t.addDeco( (Deco)tc.newInstance() );
	}
	
	private void setFog( Tile t, int x, int y ) {
		ITileCreator tc = creatorMap.getFogCreator( ColorIntUtil.getBValue( this.getMapData( x, y ).getMapData( x, y ) ) );
		if( tc != null )
			t.addFog( (Fog)tc.newInstance() );
	}

	public void saveMaps() {
		mapDataDist.saveMaps();
	}
	
	public ITile translateMapColor( int color ) {
		ITileCreator tc = creatorMap.getCreator( ColorIntUtil.getAValue( color ), ColorIntUtil.getRValue( color ) );
		if( tc != null )
			return tc.newInstance();
		return null;
	}

	public TileCreatorGen getCreatorMap() {
		return creatorMap;
	}

	public MapData getMapData( int tx, int ty ) {
		return mapDataDist.getMapData( tx, ty );
	}
	
}
